const BaseRest = require('./base.js');

module.exports = class extends BaseRest {
  // POST:
  // {
  //   "username":"root",
  //   "password":"123456"
  //   }
  
  // token 生成
  // {
  //   "errno": 0,
  //   "errmsg": "",
  //   "data": {
  //     "token":
  // "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5mbyI6eyJpZCI6MSwidXNlcm5hbWUiOiJyb290IiwiZW1haWwiOm51bGwsInFxIjoiIiwiZ2l0aHViIjpudWxsLCJ6aGlodSI6bnVsbCwid2VpYm8iOm51bGwsInBhc3N3b3JkIjoiMjRkOGNlZTllZDc5M2I5ZjgxOGI2YzRiNjdhYWU5YWEiLCJlbmNyeXB0IjoiTWplNXNvd1Q3In0sImlhdCI6MTUyOTkwMzcwOSwiZXhwIjoxNTI5OTA3MzA5fQ.VsWQKaFqkXmjbPTflsnXLfB5w7W1ZJGFNfDwNQ97QxU"
  // } }
  async postAction() {
    const SESSION_KEY = 'userInfo';
    await this.session(SESSION_KEY, null);
    
    //const ip = this.ctx.ip;
    
    const account = this.post('username');
    const password = this.post('password');
    let loginType = this.post('type');
    
    if (think.isEmpty(loginType)) {
      if (/^1[34578]\d{9}$/.test(account)) {
        loginType = 'mobile';
      } else if (/^([a-zA-z_-])+@([a-zA-z0-9_-]+[.])+([a-zA-z0-9]){2,5}$/.test(
          account)) {
        loginType = 'email';
      } else {
        loginType = think.isEmpty(loginType) ? 'username' : loginType;
      }
    } else {
      loginType = 'username';
    }
    
    // let loginType = 'username';
    
    // 支持账号、Email和手机号码登录
    // 后续支持第三方登录如：QQ，微信
    let map = {};
    switch (loginType.toLowerCase()) {
      case 'username':
        map = {
          username: account,
        };
        break;
      case 'email':
        map = {
          email: account,
        };
        break;
      case 'mobile':
        map = {
          mobile: account,
        };
        break;
      default:
        return this.fail('登录方式设置错误');
    }
    
    const user = this.model('user');
    const userInfo = await user.where(map).find();
    if (think.isEmpty(userInfo)) {
      return this.fail('用户不存在');
    }
    const result = user.verifyPassword(userInfo, password);
    if (think.isEmpty(result)) {
      user.where(map).increment('login_fail_count');
      return this.fail('密码不正确');
    }
    
    //const last_login_time = Math.round(new Date().getTime() / 1000);
    const last_login_time = think.service('utils').getTime();
    user.where(map).update({
      last_login_ip: this.ctx.ip,
      last_login_time: last_login_time,
      login_count: userInfo.login_count + 1,
    });
    userInfo.last_login_time = last_login_time;
    const token = await this.session(SESSION_KEY, userInfo);
    return this.success({
      token: token, username: userInfo.username,
    });
    //return this.success({ token: token, userInfo: userInfo });
  }
};
